package com.qyhl.shop.shop.search;

import android.annotation.SuppressLint;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.makeramen.roundedimageview.RoundedImageView;
import com.orhanobut.hawk.Hawk;
import com.qyhl.shop.R;
import com.qyhl.shop.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.CommonDialog;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.shop.ShopListBean;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterPathConstant.SHOP_SEARCH)
public class ShopSearchActivity extends BaseActivity implements ShopSearchContract.ShopSearchView {
    @BindView(R2.id.search_bar)
    EditText searchBar;
    @BindView(R2.id.history_flowlayout)
    TagFlowLayout historyFlowlayout;
    @BindView(R2.id.history_layout)
    RelativeLayout historyLayout;
    @BindView(R2.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;

    private ShopSearchPresenter mPresenter;

    private String keyWords;

    private List<String> keyHistory = new ArrayList<>();

    private CommonAdapter<ShopListBean> commonAdapter;

    private List<ShopListBean> mDataList = new ArrayList<>();

    private int page = 1;

    @Override
    protected int getContentView() {
        return R.layout.shop_activity_search;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        loadMask.setStatus(LoadingLayout.Success);

        mPresenter = new ShopSearchPresenter(this);

        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setRefreshFooter(new ClassicsFooter(this));
        refresh.setEnableLoadMore(true);

        setHistory();

        recycleView.setLayoutManager(new LinearLayoutManager(this));
        recycleView.setAdapter(commonAdapter = new CommonAdapter<ShopListBean>(this, R.layout.shop_item_shop_list, mDataList) {
            @Override
            protected void convert(ViewHolder holder, ShopListBean bean, int position) {
                holder.setText(R.id.title, bean.getName());

                holder.setText(R.id.address, bean.getAddress());

                holder.setText(R.id.contact, bean.getPhone());

                if (bean.isTop()) {
                    holder.setVisible(R.id.top_tag, true);
                } else {
                    holder.setVisible(R.id.top_tag, false);
                }

                RoundedImageView cover = holder.getView(R.id.cover);
                Glide.with(ShopSearchActivity.this)
                        .load(bean.getImageUrl())
                        .apply(new RequestOptions().error(R.drawable.cover_normal_default).placeholder(R.drawable.cover_normal_default))
                        .into(cover);

                RecyclerView recyclerView = holder.getView(R.id.tag_recycler);
                recyclerView.setLayoutManager(new LinearLayoutManager(ShopSearchActivity.this, RecyclerView.HORIZONTAL, false));
                recyclerView.setAdapter(new CommonAdapter<String>(ShopSearchActivity.this, R.layout.shop_item_shop_list_tag, bean.getCouponList()) {

                    @Override
                    protected void convert(ViewHolder holder, String s, int position) {
                        holder.setText(R.id.tag_name, s);
                    }
                });
            }
        });
    }

    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                page = 1;
                mPresenter.doSearch(keyWords, page);
            }
        });

        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                mPresenter.doSearch(keyWords, page);
            }
        });

        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.doSearch(keyWords, page);
            }
        });

        searchBar.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                keyWords = s.toString();
            }
        });

        searchBar.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {//按下搜索
                    keyWords = searchBar.getText().toString();
                    if (StringUtils.isEmpty(keyWords)) {
                        showToast("搜索内容不能为空！");
                    } else {
                        page = 1;
                        mPresenter.doSearch(keyWords, page);
                        hideInput();
                    }
                }
                return false;//返回true，保留软键盘。false，隐藏软键盘
            }

        });

        historyFlowlayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                keyWords = keyHistory.get(position);
                page = 1;
                mPresenter.doSearch(keyWords, page);
                return false;
            }
        });

        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                ARouter.getInstance()
                        .build(ARouterPathConstant.SHOP_SHOP_DETAIL)
                        .withInt("shopId", mDataList.get(i).getId())
                        .navigation();

                ActionLogUtils.getInstance().onEvent(ActionConstant.SHOP_FROM_LIST, mDataList.get(i).getId());
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                return false;
            }
        });

    }

    @Override
    public void setList(List<ShopListBean> beanList) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        historyLayout.setVisibility(View.GONE);
        loadMask.setVisibility(View.VISIBLE);
        if (beanList == null) {
            setError("暂无任何内容!");
            return;
        }

        if (page != 1) {
            refresh.finishLoadMore();
        } else {
            boolean isNew = true;
            if (Hawk.contains("shop_history")) {
                List<String> historyList = Hawk.get("shop_history");
                for (int i = 0; i < historyList.size(); i++) {
                    if (historyList.get(i).equals(keyWords)) {
                        isNew = false;
                    }
                }
                if (isNew) {
                    historyList.add(0, keyWords);
                    if (historyList.size() > 10) {
                        List<String> list = historyList.subList(0, 10);
                        Hawk.put("shop_history", list);
                    } else {
                        Hawk.put("shop_history", historyList);
                    }
                    setHistory();
                }
            } else {
                List<String> historyList = new ArrayList<>();
                historyList.add(keyWords);
                Hawk.put("shop_history", historyList);
            }


            refresh.finishRefresh();
            mDataList.clear();
        }
        page++;
        mDataList.addAll(beanList);
        commonAdapter.notifyDataSetChanged();
    }

    @Override
    public void setError(String msg) {
        if (page != 1) {
            refresh.finishLoadMore();
            if (!NetUtil.isNetworkAvalible(this)) {
                showToast("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {
                showToast(msg);
            } else {
                showToast(msg);
            }
        } else {
            refresh.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            loadMask.setReloadButtonText("点击重试~");
            if (!NetUtil.isNetworkAvalible(this)) {
                loadMask.setErrorImage(R.drawable.error_network);
                loadMask.setErrorText("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {
                loadMask.setErrorImage(R.drawable.empty_content);
                loadMask.setErrorText(msg);
            } else {
                loadMask.setErrorImage(R.drawable.error_content);
                loadMask.setErrorText(msg);
            }
        }
    }

    private void setHistory() {
        keyHistory.clear();
        List<String> stringList = Hawk.get("shop_history");
        if (stringList != null && stringList.size() > 0) {
            historyLayout.setVisibility(View.VISIBLE);
            keyHistory.addAll(stringList);

            historyFlowlayout.setAdapter(new TagAdapter<String>(keyHistory) {
                @SuppressLint("SetTextI18n")
                @Override
                public View getView(FlowLayout parent, int position, String str) {
                    TextView tv = (TextView) LayoutInflater.from(ShopSearchActivity.this).inflate(R.layout.shop_search_item_history,
                            historyFlowlayout, false);
                    tv.setText(str);
                    return tv;
                }
            });
        } else {
            historyLayout.setVisibility(View.GONE);
        }
    }


    @OnClick({R2.id.back_btn, R2.id.delete_btn})
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.back_btn) {
            finish();
        } else if (viewId == R.id.delete_btn) {
            new CommonDialog.Builder(ShopSearchActivity.this)
                    .setTitle("提示", R.color.global_black_lv1)
                    .setMessage("是否确定删除历史记录？", R.color.global_black_lv2)
                    .setPositiveButton("确定", v -> {
                        Hawk.delete("shop_history");
                        setHistory();
                    }, R.color.global_base)
                    .setNegativeButton("取消", null, R.color.global_gray_lv2).show();
        }
    }
}
